import axios from 'axios';

let isRefreshing = false;
let refreshSubscribers = [];

function onRefreshed(token) {
  refreshSubscribers.forEach(cb => cb(token));
  refreshSubscribers = [];
}

function addRefreshSubscriber(cb) {
  refreshSubscribers.push(cb);
}

// 动态获取 API 基础 URL
const getApiBaseUrl = () => {
  // 优先使用环境变量
  if (import.meta.env.VITE_API_BASE_URL) {
    return import.meta.env.VITE_API_BASE_URL
  }
  
  // 检查当前域名，如果是远程访问，自动使用对应的远程API
  const currentHost = window.location.hostname
  const currentProtocol = window.location.protocol
  
  // 如果是通过远程域名访问，自动使用对应的远程API
  if (currentHost.includes('cpolar.top') || currentHost.includes('cos-website')) {
    if (currentHost === '1f47e7a6.r9.cpolar.top') {
      return 'https://69f63df3.r9.cpolar.top'  // 使用新的远程接口作为后端
    } else if (currentHost === '6c46076a.r9.cpolar.top') {
      return 'https://6c46076a.r9.cpolar.top'  // 原有远程接口
    } else if (currentHost === '69f63df3.r9.cpolar.top') {
      return 'https://69f63df3.r9.cpolar.top'  // 新增远程接口
    } else if (currentHost.includes('cos-website')) {
      return 'https://lutiance-1371863414.cos-website.ap-beijing.myqcloud.com'  // 生产环境
    }
  }
  
  // 开发环境：支持本地和远程
  if (import.meta.env.MODE === 'development') {
    const useRemote = localStorage.getItem('use_remote_api') === 'true'
    const customRemote = localStorage.getItem('custom_remote_api')
    
    if (customRemote) {
      return customRemote  // 用户自定义远程接口
    }
    
    return useRemote 
      ? 'https://69f63df3.r9.cpolar.top'  // 新的远程接口
      : 'http://localhost:3005'           // 本地接口
  }
  
  // 生产环境：支持多种后端地址
  if (import.meta.env.MODE === 'production') {
    // 可以从 localStorage 获取用户设置的后端地址
    const customApiUrl = localStorage.getItem('custom_api_url')
    if (customApiUrl) {
      return customApiUrl
    }
    
    // 检查是否使用新的远程接口
    const useNewRemote = localStorage.getItem('use_new_remote_api') === 'true'
    if (useNewRemote) {
      return 'https://1f47e7a6.r9.cpolar.top'  // 新的HTTPS远程接口
    }
    
    // 默认使用远程接口
    return 'https://69f63df3.r9.cpolar.top'
  }
  
  // 默认本地接口
  return 'http://localhost:3005'
}

const instance = axios.create({ 
  baseURL: getApiBaseUrl(), 
  withCredentials: true 
});

instance.interceptors.request.use(config => {
  const token = localStorage.getItem('access_token');
  if (token) config.headers.Authorization = `Bearer ${token}`;
  return config;
});

instance.interceptors.response.use(
  res => res,
  async error => {
    const { config, response } = error;
    if (response && response.status === 401 && !config._retry) {
      if (!isRefreshing) {
        isRefreshing = true;
        try {
          const { data } = await axios.post('/ltc/refresh-token', {}, { withCredentials: true });
          localStorage.setItem('access_token', data.accessToken);
          onRefreshed(data.accessToken);
        } catch (e) {
          localStorage.removeItem('access_token');
          window.location.href = '/login';
        } finally {
          isRefreshing = false;
        }
      }
      return new Promise(resolve => {
        addRefreshSubscriber(token => {
          config.headers.Authorization = `Bearer ${token}`;
          config._retry = true;
          resolve(instance(config));
        });
      });
    }
    return Promise.reject(error);
  }
);

export default instance; 